﻿// *********************************************************************
// * Copyright © 2013 Thomas Due
// *
// * This file is the property of Thomas Due and may not be 
// * distributed without the written consent of the author.    
// ********************************************************************

using System;
using System.Data;
using System.Windows.Forms;
using SqlPad.Library.Interfaces;

namespace SqlPad.UI
{
    public partial class SqlPadMainForm : Form
    {
        private readonly IQueryFactory _queryFactory;

        public SqlPadMainForm(IQueryFactory queryFactory) : this()
        {
            if (queryFactory == null)
            {
                throw new ArgumentNullException("queryFactory");
            }
            _queryFactory = queryFactory;
        }

        public SqlPadMainForm()
        {
            InitializeComponent();
        }

        private void ExecuteQueryButton_Click(object sender, EventArgs e)
        {
            IQueryResult<DataTable> result = null;
            try
            {
                var query = _queryFactory.CreateQuery<DataTable>();
                query.ConnectionString = ConnectionStringTextBox.Text;
                result = query.Run(QueryTextBox.Selection.Length > 0
                                           ? QueryTextBox.Selection.Text
                                           : QueryTextBox.Text);

                toolStripStatusLabel1.Text = string.Format("Rows returned: {0:N0}", result.RowsReturned);
                toolStripStatusLabel2.Text = string.Format("Rows returned: {0:g}", result.ExecuteTime);

                var transform = _queryFactory.CreateTransform<DataTable>();

                htmlPanel1.Text = transform.Transform(result);

                ResultTabControl.SelectTab(ResultTabPage);
                ResultTabPage.Focus();
            }
            catch (Exception ex)
            {
                ResultMessageTextBox.Text = ex.ToString();
                ResultTabControl.SelectTab(MessageTabPage);
                MessageTabPage.Focus();
            }
            finally
            {
                if (result != null && result.Result != null)
                {
                    result.Result.Dispose();
                }
            }
        }
    }
}
